﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using ProgNetComponents.Data.SqlCe;
using DevExpress.XtraTab;

namespace BuildHelper.Work.Tools
{
    public partial class SecurityCheckForm : XtraForm
    {
        private bool isClosing = false;

        public SecurityCheckForm()
        {
            InitializeComponent();
            Systems.Columns.Add("System");
            gcMain.DataSource = Systems;
        }
        Dictionary<string, SystemSecurityOptions> dic1 = new Dictionary<string, SystemSecurityOptions>();
        Dictionary<string, SystemSecurityOptions> dic2 = new Dictionary<string, SystemSecurityOptions>();

        DataTable Systems = new DataTable();
        Setup.Brancze.BranczeDataSet ds = new Setup.Brancze.BranczeDataSet();
        Setup.Brancze.BranczeDataSet ds2 = new Setup.Brancze.BranczeDataSet();
                
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            isClosing = true;
            base.OnFormClosing(e);
        }

        private void Clear(bool wyniki)
        {
            if (wyniki)
            {
                foreach (XtraTabPage p in tabWyniki.TabPages.ToArray())
                    p.Dispose();
                tabWyniki.TabPages.Clear();
            }
            else
            {
                foreach (XtraTabPage p in tabWynikiCompare.TabPages.ToArray())
                    p.Dispose();

                tabWynikiCompare.TabPages.Clear();
            }
        }

        private void AddPage(XtraTabControl tab, string sys, string text, List<string> list)
        {
            if (list.Count > 0)
            {
                XtraTabPage p = null;
                MemoEdit me = null;
                foreach (XtraTabPage x in tab.TabPages)
                {
                    if (x.Text == sys + " " + text)
                    {
                        p = x;
                        p.Controls[0].Text = string.Empty;
                        me = p.Controls[0] as MemoEdit;
                    }
                }
                if (p == null)
                {
                    p = new XtraTabPage();
                    p.Text = sys + " " + text;
                    me = new MemoEdit();
                    me.Dock = DockStyle.Fill;
                    me.Properties.ReadOnly = true;
                    p.Controls.Add(me);
                    tab.TabPages.Add(p);
                }
                me.Lines = list.ToArray();
                list.Clear();
            }
        }
        private void lueBrancz_EditValueChanged(object sender, EventArgs e)
        {
            Clear(true);
            ReadBrancz(true);
        }

        private void lueBrancz2_EditValueChanged(object sender, EventArgs e)
        {
            Clear(false);
            ReadBrancz(false);
        }
        private bool GetData(string stm, bool brancz1)
        {
            var dic = (brancz1 ? dic1 : dic2);
            if (dic.ContainsKey(stm))
                return true;

            var dsx = brancz1 ? ds : ds2;
            if (dsx.STP_BRANCZE.Rows.Count == 1)
            {
                DataRow r = dsx.STP_BRANCZE[0];
                string katalog = r["STP_BR_KATALOG"].AsString().TrimEnd('\\');
                string gene = katalog + "\\nd_src\\gene";
                string apps = katalog + "\\nd_src\\gene\\apps";
                string brancz= brancz1?lueBrancz.EditValue.AsString():lueBrancz2.EditValue.AsString();

                var s = SystemSecurityOptions.GetSystemSecurityOptions(apps, stm, brancz);
                if (s != null)
                {
                    dic.Add(stm, s);
                    return true;
                }
            }
            return false;
        }
        private void Sprawdz(string stm, bool brancz1)
        {
            SystemSecurityOptions sec = null;
            if (!GetData(stm, brancz1))
            {
                this.ShowDxInfoDialog("Nie można odczytać security brancza " + (brancz1 ? "1" : "2"));
                return;
            }
            if (brancz1)
            {
                if (dic1.ContainsKey(stm))
                    sec = dic1[stm];
            }
            else
            {
                if (dic2.ContainsKey(stm))
                    sec = dic2[stm];
            }
            if (sec != null)
            {
                var list = sec.Check();
                foreach (var l in list)
                {
                    AddPage(tabWyniki, sec.Brancz + "_" + stm, l.Name, l);
                }
            }
            else
            {
                this.ShowDxInfoDialog("Nie można odczytać security brancza " + (brancz1 ? "1" : "2"));
                return;
            }
        }
        private void Porownaj(string stm)
        {
            SystemSecurityOptions sec1 = null;
            if (!GetData(stm, true))
            {
                this.ShowDxInfoDialog("Nie można odczytać security brancza 1");
                return;
            }
            if (!GetData(stm, false))
            {
                this.ShowDxInfoDialog("Nie można odczytać security brancza 2");
                return;
            }
            if (dic1.ContainsKey(stm))
                sec1 = dic1[stm];
            if (sec1 != null)
            {
                SystemSecurityOptions sec2 = null;
                if (dic2.ContainsKey(stm))
                    sec2 = dic2[stm];
                if (sec2 != null)
                {
                    var l = sec1.Compare(sec2);
                    foreach (var li in l)
                        AddPage(tabWynikiCompare, stm, li.Name, li);
                }
                else
                {
                    this.ShowDxInfoDialog("Nie można odczytać security brancza 2");
                    return;
                }
            }
            else
            {
                this.ShowDxInfoDialog("Nie można odczytać security brancza 2");
                return;
            }
        }
        private void repItemCompare_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DataRow r = gvMain.GetFocusedDataRow();
            if (r != null)
            {
                if (gvMain.FocusedColumn == colSprawdz)
                {
                    Sprawdz(r["System"].AsString(), true);
                } 
                if (gvMain.FocusedColumn == colSprawdzBrancz2)
                {
                    Sprawdz(r["System"].AsString(), false);
                }
                if (gvMain.FocusedColumn == colCompare)
                {
                    Porownaj(r["System"].AsString());
                }
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            Clear(true);
            Clear(false);
        }
        private void ReadBrancz(bool brancz1)
        {
            Setup.Brancze.BranczeDataSet dsx;
            string brancz;
            Dictionary<string, SystemSecurityOptions> dic;
            if (brancz1)
            {
                dsx = ds;
                brancz = lueBrancz.EditValue.AsString();
                dic = dic1;
                Systems.Clear();
            }
            else
            {
                dsx = ds2;
                brancz = lueBrancz2.EditValue.AsString();
                dic = dic2;
            }
            if (brancz.IsNull())
                return;

            dic.Clear();
            dsx.Clear();
            using (SqlCeDataManager sqlCeDataManager1 = new SqlCeDataManager())
            {
                sqlCeDataManager1.AutoLogExceptions = true;
                sqlCeDataManager1.FillTable(dsx.STP_BRANCZE, "SELECT * FROM STP_BRANCZE WHERE STP_BR_NAZWA = " + brancz.EscapeSql());
                sqlCeDataManager1.FillTable(dsx.STP_BRANCZE_APPS, "SELECT * FROM STP_BRANCZE_APPS WHERE STP_BR_APP_BRANCZ= " + brancz.EscapeSql());

                if (dsx.STP_BRANCZE.Rows.Count == 1)
                {
                    DataRow r = dsx.STP_BRANCZE[0];
                    string katalog = r["STP_BR_KATALOG"].AsString().TrimEnd('\\');
                    string gene = katalog + "\\nd_src\\gene";
                    string apps = katalog + "\\nd_src\\gene\\apps";
                    string sys;
                    if (brancz1)
                    {
                        foreach (DataRow appRow in ds.STP_BRANCZE_APPS.Rows)
                        {
                            sys = appRow["STP_BR_APP_APP"].ToString();
                            if (SystemSecurityOptions.HasOptions(apps, sys))
                                Systems.Rows.Add(sys);
                        }
                    }
                }
            }
        }

        private void btnZapisz_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string folder = folderBrowserDialog1.SelectedPath.TrimEnd('\\');
                string file;
                foreach (XtraTabPage p in tabWyniki.TabPages)
                {
                    file = folder + "\\" + p.Text.MakeValidFileName() + ".txt";
                    p.Controls[0].Text.WriteToFile(file);
                }
                foreach (XtraTabPage p in tabWynikiCompare.TabPages)
                {
                    file = folder + "\\" + (lueBrancz.EditValue.AsString() + "-" + lueBrancz2.EditValue.AsString() + "_" + p.Text).MakeValidFileName() + ".txt";
                    p.Controls[0].Text.WriteToFile(file);
                }
                if (this.ShowDxYNQuestionDialog("Otworzyć katalog?") == System.Windows.Forms.DialogResult.Yes)
                    GlobalTools.FilesTools.OpenDirs(folder);
            }
        }
       
    }
}
